<?php

namespace App\Http\Middleware;


use App\Models\User;
use Closure;

class LoginMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!$request->hasHeader('X-AUTHTOKEN')) {
            return ['code' => 500, 'msg' => '您还没有登录, 请登录', 'data' => []];
        }
        if (!$user = User::where('token', $request->header('X-AUTHTOKEN'))->first()) {
            return ['code' => 500, 'msg' => 'token过期或失效, 请重新登录', 'data' => []];
        }

        $request->setUserResolver(function() use($user){
            return $user;
        });


        return $next($request);
    }
}
